package org.nuxeo.gwt.habyt.templates.client.widgets;

import java.util.Date;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.HasName;
import com.google.gwt.user.client.ui.HasText;
import com.google.gwt.user.client.ui.PopupPanel;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.datepicker.client.DatePicker;

public class DateBox extends FlowPanel implements HasName, HasText,
        ClickHandler, ValueChangeHandler<Date> {

    protected String name;

    protected TextBox text;

    protected Button btn;

    protected DateTimeFormat format;

    protected PopupPanel popup;

    protected DatePicker picker;

    public DateBox(DateTimeFormat format) {
        DOM.setStyleAttribute(getElement(), "display", "inline-block");
        this.format = format;
        text = new TextBox();
        // btn = new Button("<img src=\""
        // + BaseURL.getResourcePath("images/arrow-down.gif")
        // + "\" alt=\"Select Date\"/>", this);
        btn = new Button("...");
        btn.addClickHandler(this);
        add(text);
        add(btn);
        picker = new DatePicker();
        popup = new PopupPanel();
        popup.setAutoHideEnabled(true);
        popup.addAutoHidePartner(getElement());
        popup.setWidget(picker);
        popup.setStyleName("dateBoxPopup");
        btn.addStyleName("dateBoxButton");
        picker.addValueChangeHandler(this);
        text.setReadOnly(true);
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getText() {
        return text.getText();
    }

    public void setText(String text) {
        this.text.setText(text);
    }

    public Date getValue() {
        return picker.getValue();
    }

    public void setValue(Date value) {
        picker.setValue(value);
    }

    public void onClick(ClickEvent event) {
        Date current = null;
        try {
            current = format.parse(text.getText());
        } catch (Exception e) {
            current = new Date();
        }
        if (current == null) {
            current = new Date();
        }
        picker.setCurrentMonth(current);
        picker.setValue(current);
        popup.showRelativeTo(btn);
    }

    public void onValueChange(ValueChangeEvent<Date> event) {
        text.setText(format.format(picker.getValue()));
        popup.hide();
    }
}
